package cn.edu.tju.cas.service.impl;

import cn.edu.tju.cas.dao.GroupDao;
import cn.edu.tju.cas.dao.GroupFormDao;
import cn.edu.tju.cas.dao.UserGroupApplyDao;
import cn.edu.tju.cas.dao.UserGroupFormValueDao;
import cn.edu.tju.cas.dao.impl.UserGroupFormValueDaoImpl;
import cn.edu.tju.cas.entity.UserEntity;
import cn.edu.tju.cas.entity.UserGroupApplyEntity;
import cn.edu.tju.cas.entity.UserGroupFormValueEntity;
import cn.edu.tju.cas.service.ApplyService;
import cn.edu.tju.cas.util.Constants;
import cn.edu.tju.cas.util.NewApply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by catold on 16/3/12.
 */
@Service("applyService")
public class ApplyServiceImpl extends BaseServcieImpl<UserGroupApplyEntity, UserGroupApplyDao> implements ApplyService {
    @Autowired
    private UserGroupApplyDao userGroupApplyDao;

    @Autowired
    private GroupFormDao groupFormDao;

    @Autowired
    private UserGroupFormValueDao userGroupFormValueDao;

    @Autowired
    private GroupDao groupDao;

    @Resource(name = "userGroupApplyDao")
    public void setDao(UserGroupApplyDao userGroupApplyDao) {
        super.setDao(userGroupApplyDao);
    }

    @Override
    public List<UserGroupApplyEntity> queryByStateAndRelation(int state) {
        return userGroupApplyDao.queryByState(state);
    }

    @Override
    public UserGroupApplyEntity saveNewApply(UserEntity userEntity,NewApply newApply) {


        // 在 Service 层  需要事务支持
        UserGroupApplyEntity userGroupApplyEntity = new UserGroupApplyEntity();
        if(newApply == null || newApply.getGroupId() < 0  || newApply.getUserGroupFormValues() == null|| newApply.getUserGroupFormValues().size() <= 0){
            return null;
        }

        // 生成一条新的 申请 Apply

        // groupId
        int groupId = newApply.getGroupId();
        // status
        int status = 0;
        userGroupApplyEntity.setStatus(0);
        // many-to-one userEntity
        userGroupApplyEntity.setUserEntity(userEntity);
        // many-to-one groupEntity
        userGroupApplyEntity.setGroupEntity(groupDao.findById(groupId));

        Set<UserGroupFormValueEntity> userGroupFormValueEntities = newApply.getUserGroupFormValues();


//        String urls = "";
//        for(UserGroupFormValueEntity item :userGroupFormValueEntities){
//            if(item.getGroupFormId() == -1){
//              urls = item.getValue();
//            }
//        }

        Set<UserGroupFormValueEntity> userGroupFormValueEntity = new HashSet<>();
        for(UserGroupFormValueEntity item :userGroupFormValueEntities){
            System.out.println(item.getValue());
//            if(item.getValue().equals("请在下方选择上传文件")){
//                System.out.println("文件url: "+ item.getValue());
//               item.setValue(urls);
//            }
            if(item.getGroupFormId() != -1){
                userGroupFormValueEntity.add(item);
            }
        }

        // one-to-many
        userGroupApplyEntity.setUserGroupFormValues(userGroupFormValueEntity);

        userGroupApplyDao.save(userGroupApplyEntity);

        return userGroupApplyEntity;
    }

    @Override
    public List<UserGroupApplyEntity> findAllAndRelation() {
        return null;
    }

    @Override
    public List<UserGroupApplyEntity> getUserGroupApply(int userid) {
        return userGroupApplyDao.getUserApply(userid);
    }


    @Override
    public List<UserGroupApplyEntity> getCertifiedUserGroupApply(int userid) {
        return userGroupApplyDao.queryByUserAndState(userid,1);
    }

    @Override
    public void removeAllRolesByUserId(int userId) {
        List<UserGroupApplyEntity> userGroupApplies = userGroupApplyDao.queryByUserAndState(userId,1);
        if(userGroupApplies!=null && userGroupApplies.size() > 0){
            for(UserGroupApplyEntity apply:userGroupApplies){
                System.out.println("删除 apply："+ apply.getUserGroupApplyId());
                userGroupApplyDao.deleteById(apply.getUserGroupApplyId());
            }
        }
    }


    //单文件上传
    @Override
    public  String uploadFile( MultipartFile file,String targetDir,String baseUrl){
        try{
            System.out.println("传进来的" + targetDir);
            String uploadFileName = file.getOriginalFilename();
            uploadFileName = uploadFileName.replaceAll("\\s+","");

            System.out.println("处理后的file name is："+ uploadFileName);

            InputStream isRef = file.getInputStream();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
            String getDateString = sdf.format(new Date());
//            String fileName = getDateString + "_" + System.nanoTime() + "_" + uploadFileName;

            // 保存在硬盘上的文件名儿（文件）
            String fileName = getDateString + "_" + uploadFileName;

            File targetFile = new File(targetDir,fileName);// 目录结构： upload/image/2015_10_23/xxx.jpg

            if(!targetFile.exists()){
                targetFile.mkdirs();
            }

            if (file.getSize() > 0) {
                //写入目标文件
//                FileOutputStream fosRef = new FileOutputStream(targetFile);
//                IOUtils.copy(isRef, fosRef);
                file.transferTo(targetFile);//写入目标文件
            }else{
                return null;
            }

            // filePath 此处是文件存储路径，+主机名+端口号+应用名，可以直接访问，浏览器可以直接访问的地址
//            String filePath =baseUrl + "/" + fileName.substring(0, fileName.lastIndexOf("."))+".mp4";
            String filePath =baseUrl + "/" + fileName;
            return filePath;
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }
}
